//
//  CourseDetialViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/28.
//

#import "CourseDetialViewController.h"
#import "CourseGrammarViewController.h"
#import "CourseDetialTableViewController.h"
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"

@interface CourseDetialViewController ()<
UIScrollViewDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate,
JPAPIManagerCallBackDelegate,
CourseDetialTableViewControllerDelegate
>

@property(nonatomic,strong)UIButton *seeBtn;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIButton *allBtn;
@property(nonatomic,strong)UIButton *learnBtn;
@property(nonatomic,strong)UIView *allLine;
@property(nonatomic,strong)UIView *learnLine;
@property(nonatomic,strong)UIScrollView *bgScorllView;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,assign)BOOL isClick;
@property(nonatomic,strong)CourseDetialTableViewController *allTVC;
@property(nonatomic,strong)CourseDetialTableViewController *learnTVC;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property (nonatomic, strong) dispatch_queue_t work_queue;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)CourseDetialTableViewController *speakTVC;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property (nonatomic,assign) BOOL isPlaying;

@end

@implementation CourseDetialViewController

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    
    self.sel_index = 0;
    
    [self initPlay];
    [self NuiTtsInit];
    
    [self createUI];
    
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("CourseDetialViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}

#pragma mark - 更新语音合成参数配置
-(void)UpdateTtsParams:(NSString *)content{
    
    int chars = 0;
    // 支持一次性合成300字符以内的文字，其中1个汉字、1个英文字母或1个标点均算作1个字符，
    // 超过300个字符的内容将会截断。所以请确保传入的text小于300字符(不包含ssml格式)。
    // 长短文本语音合成收费不同，请注意。
    // 300字这个截点可能会变更，以官网文档为准。
    chars = [self.nui nui_tts_get_num_of_chars: [content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成 长文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成 短文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}

#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.speakTVC){
                    [self.speakTVC stopPlayAnimation];
                }
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
           
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.speakTVC){
            [self.speakTVC stopPlayAnimation];
        }
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.speakTVC){
                [self.speakTVC stopPlayAnimation];
            }
        }
    });

}

#pragma mark - 语音合成读文本
-(void)speakText:(CourseDetialTableViewController *)vc andText:(NSString *)text{
   self.speakTVC = vc;
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
                
                [self UpdateTtsParams:text];
                
                [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
            }
        });
    }
}

#pragma mark - 停止语音播放
-(void)stopSpeak:(CourseDetialTableViewController *)vc{
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        [self.avPlayer seekToTime:kCMTimeZero];
    }
}

#pragma mark - 播放单词读音
-(void)playAudio:(CourseDetialTableViewController*)vc andAudio:(NSString*)audio{
    self.speakTVC = vc;
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:audio]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    if(self.avPlayer){
        [self.avPlayer pause];
        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
    }else{
        self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    [self.avPlayer play];
    self.isPlaying = YES;
}


-(void)playToEndTime:(NSNotification*)notifi{
    if(self.speakTVC){
        [self.speakTVC stopPlayAnimation];
    }
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            [JPProgressHUD showMsg:@"播放失败"];
            if(self.speakTVC){
                [self.speakTVC stopPlayAnimation];
            }
        }
    }
}



#pragma mark - 界面
-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.seeBtn = [[UIButton alloc]init];
    [self.seeBtn setImage:[UIImage imageNamed:@"mine_collect_see"] forState:UIControlStateNormal];
    [self.seeBtn setImage:[UIImage imageNamed:@"mine_collect_unsee"] forState:UIControlStateSelected];
    [self.seeBtn addTarget:self action:@selector(seeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:self.seeBtn];
    [self.seeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@34);
        make.right.mas_equalTo(@-11);
        make.bottom.mas_equalTo(@-5);
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontPingFangSCMedium(17);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.text = [NSString stringWithFormat:@"%@ (%@) %@",self.bookModel.name,self.bookModel.volumeName,self.courseModel.courseName];
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@20);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+12);
        make.height.mas_equalTo(@24);
        make.right.mas_equalTo(@-20);
    }];
    
    if(self.courseModel.grammarFile&&![self.courseModel.grammarFile isEqualToString:@""]){
        self.bgScorllView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+91,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-91-83)];
    }else{
        self.bgScorllView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+91,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-91)];
    }
    self.bgScorllView.pagingEnabled = YES;
    self.bgScorllView.backgroundColor = [UIColor whiteColor];
    self.bgScorllView.contentSize = CGSizeMake(2*self.currentAvailableWidth,0);
    self.bgScorllView.delegate = self;
    self.bgScorllView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.bgScorllView];
    
    CGFloat btn_w = (self.currentAvailableWidth-60)/2.0;
    NSArray *arr = @[@"全部",@"已学习"];
    for(NSInteger i = 0; i< arr.count;i ++){
        UIButton *btn = [[UIButton alloc]init];
        if(i == 0){
            [btn setTitle:[NSString stringWithFormat:@"%@(%@)",arr[i],self.courseModel.sum] forState:UIControlStateNormal];
        }else{
            [btn setTitle:[NSString stringWithFormat:@"%@(%@)",arr[i],self.courseModel.finish] forState:UIControlStateNormal];
        }
        [btn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
        [btn setTitleColor:KThemeColor forState:UIControlStateSelected];
        btn.tag = 100+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20+i*btn_w);
            make.width.mas_equalTo(btn_w);
            make.height.mas_equalTo(@44);
            make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+46);
        }];
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = KThemeColor;
        line.layer.cornerRadius = 1;
        line.layer.masksToBounds = YES;
        [btn addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(@20);
            make.height.mas_equalTo(@2);
            make.bottom.mas_equalTo(@0);
            make.centerX.mas_equalTo(btn);
        }];
        if(i == self.sel_index){
            btn.titleLabel.font = JPUIFontPingFangSCMedium(15);
            btn.selected = YES;
            line.hidden = NO;
        }else{
            btn.titleLabel.font = JPUIFontPingFangSCRegular(15);
            btn.selected = NO;
            line.hidden = YES;
        }
        if(i == 0){
            self.allBtn = btn;
            self.allLine = line;
        }else{
            self.learnBtn = btn;
            self.learnLine = line;
        }
        CourseDetialTableViewController *tableVC = [[CourseDetialTableViewController alloc]init];
        tableVC.view.frame = CGRectMake(i*self.currentAvailableWidth,0,self.currentAvailableWidth,self.bgScorllView.height);
        tableVC.delegate = self;
        [self addChildViewController:tableVC];
        [self.bgScorllView addSubview:tableVC.view];
        tableVC.courseId = self.courseModel.courseId;
        tableVC.isSel = self.seeBtn.selected;
        if(i == 0){
            self.allTVC = tableVC;
            tableVC.sel_index = i;
        }else{
            self.learnTVC = tableVC;
        }
       
    }
    
   
    if(self.courseModel.grammarFile&&![self.courseModel.grammarFile isEqualToString:@""]){
        UIView *bottomView = [[UIView alloc]init];
        bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:bottomView];
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(@0);
            make.height.mas_equalTo(@83);
        }];
        
        UIView *bline = [[UIView alloc]init];
        bline.backgroundColor = KbgColor;
        [bottomView addSubview:bline];
        [bline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_equalTo(@0);
            make.height.mas_equalTo(@1);
        }];
        
        UIButton *grammarBtn = [[UIButton alloc]init];
        [grammarBtn setTitle:@"本课语法" forState:UIControlStateNormal];
        [grammarBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        grammarBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
        grammarBtn.backgroundColor = KThemeColor;
        grammarBtn.layer.cornerRadius = 20;
        grammarBtn.layer.masksToBounds = YES;
        [grammarBtn addTarget:self action:@selector(grammarBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:grammarBtn];
        [grammarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@16);
            make.right.mas_equalTo(@-16);
            make.top.mas_equalTo(@5);
            make.height.mas_equalTo(@40);
        }];
    }
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];

            // 更新导航栏和背景视图的大小
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat bgScrollViewHeight = self.courseModel.grammarFile && ![self.courseModel.grammarFile isEqualToString:@""]
                ? self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 91 - 83
                : self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 91;
            self.bgScorllView.frame = CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT + 91, self.currentAvailableWidth, bgScrollViewHeight);
            self.bgScorllView.contentSize = CGSizeMake(2 * self.currentAvailableWidth, 0);

            // 更新按钮位置
            CGFloat btn_w = (self.currentAvailableWidth - 60) / 2.0;
            for (NSInteger i = 0; i < 2; i++) {
                UIButton *btn = [self.view viewWithTag:100 + i];
                [btn mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(20 + i * btn_w);
                    make.width.mas_equalTo(btn_w);
                }];
                // 更新 tableView 的位置和尺寸
                CourseDetialTableViewController *currentTVC = (i == 0) ? self.allTVC : self.learnTVC;
                currentTVC.view.frame = CGRectMake(i * self.currentAvailableWidth, 0, self.currentAvailableWidth, bgScrollViewHeight);
                currentTVC.currentAvailableWidth = self.currentAvailableWidth;
                currentTVC.currentAvailableHeight = bgScrollViewHeight;
                // 刷新 tableView 的尺寸
                [currentTVC refreshWidth];
            }
        });
    }
}


#pragma mark - 本课语法
-(void)grammarBtnClick{
    
    CourseGrammarViewController *vc = [[CourseGrammarViewController alloc]init];
    vc.file = self.courseModel.grammarFile;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 能不能看
-(void)seeBtnClick{
    
    self.seeBtn.selected = !self.seeBtn.selected;
    self.allTVC.isSel = self.seeBtn.selected;
    self.learnTVC.isSel = self.seeBtn.selected;
    
}

#pragma mark - 全部 已学
-(void)btnClick:(UIButton*)button{
    NSInteger index = button.tag - 100;
    if(index == 1){
        self.learnBtn.selected = YES;
        self.learnBtn.titleLabel.font = JPUIFontPingFangSCMedium(15);
        self.learnLine.hidden = NO;
        self.allBtn.selected = NO;
        self.allBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
        self.allLine.hidden = YES;
        self.learnTVC.sel_index = 1;
    }else{
        self.learnBtn.selected = NO;
        self.learnBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
        self.learnLine.hidden = YES;
        self.allBtn.selected = YES;
        self.allBtn.titleLabel.font = JPUIFontPingFangSCMedium(15);
        self.allLine.hidden = NO;
    }
    self.sel_index = index;
    self.isClick = YES;
    [self.bgScorllView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:NO];
}

#pragma mark - 滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isEqual:self.bgScorllView]){
        if(self.isClick == YES){
            self.isClick = NO;
        }else{
            NSInteger index = scrollView.contentOffset.x/self.currentAvailableWidth;
            if(index == 1){
                self.learnTVC.sel_index = 1;
                self.learnBtn.selected = YES;
                self.learnBtn.titleLabel.font = JPUIFontPingFangSCMedium(15);
                self.learnLine.hidden = NO;
                self.allBtn.selected = NO;
                self.allBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
                self.allLine.hidden = YES;
            }else{
                self.learnBtn.selected = NO;
                self.learnBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
                self.learnLine.hidden = YES;
                self.allBtn.selected = YES;
                self.allBtn.titleLabel.font = JPUIFontPingFangSCMedium(15);
                self.allLine.hidden = NO;
            }
            self.sel_index = index;
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
        if (self.nui) {
            [self.nui nui_tts_release];
            self.nui = nil;
        }
        [self NuiTtsInit];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


@end
